package com.fh.upload;

import com.fh.result.ResultObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Map;

@RestController
@RequestMapping("/upload")
public class UploadController {

    @Value("${filePath}")
    private  String userPhotoPath;
    @PostMapping
    public ResultObject uploadImage(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws IOException {

        //对图片进行重明名
        String oldName=file.getOriginalFilename();
        //时间戳
        long fileTimeName=System.currentTimeMillis();
        //拼接新的名称
        String newName=fileTimeName+oldName.substring(oldName.lastIndexOf("."));

        //这个是准备好的文件或保存路径
        String filePath=userPhotoPath+newName;
        //文件
        File dest=new File(filePath);
        if(!dest.getParentFile().exists()){
            dest.getParentFile().mkdirs();
        }
        //将指定文件夹保存到指定目录区
        file.transferTo(dest);
        //返回相对路径
        String realPath="/Path/"+newName;

        return ResultObject.success(realPath);
    }
}
